package com.longkier.gx_library_springboot.Controller;

import com.longkier.gx_library_springboot.Service.NoticeService;
import com.longkier.gx_library_springboot.entity.Notice;
import com.longkier.gx_library_springboot.utils.RequestUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/notice")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class NoticeController {
    private final NoticeService noticeService;

    // 获取所有公告
    @GetMapping("/all")
    public Map<String, Object> getAllNotices() {
        try {
            return RequestUtils.buildResponse(noticeService.getAllNotices(), 200);
        } catch (Exception e) {
            return RequestUtils.buildResponse("获取公告列表时发生异常", 500);
        }
    }

    // 根据ID获取公告
    @GetMapping("/{noticeId}")
    public Map<String, Object> getNoticeById(@PathVariable Long noticeId) {
        try {
            return RequestUtils.buildResponse(noticeService.getNoticeById(noticeId), 200);
        } catch (RuntimeException e) {
            return RequestUtils.buildResponse(e.getMessage(), 404);
        } catch (Exception e) {
            return RequestUtils.buildResponse("获取公告详情时发生异常", 500);
        }
    }

    // 创建公告
    @PostMapping("/create")
    public Map<String, Object> createNotice(@RequestBody Notice notice) {
        try {
            return RequestUtils.buildResponse(noticeService.createNotice(notice), 200);
        } catch (Exception e) {
            return RequestUtils.buildResponse("创建公告时发生异常", 500);
        }
    }

    // 更新公告
    @PutMapping("/{noticeId}")
    public Map<String, Object> updateNotice(@PathVariable Long noticeId, @RequestBody Notice notice) {
        try {
            return RequestUtils.buildResponse(noticeService.updateNotice(noticeId, notice), 200);
        } catch (RuntimeException e) {
            return RequestUtils.buildResponse(e.getMessage(), 404);
        } catch (Exception e) {
            return RequestUtils.buildResponse("更新公告时发生异常", 500);
        }
    }

    // 删除公告
    @DeleteMapping("/{noticeId}")
    public Map<String, Object> deleteNotice(@PathVariable Long noticeId) {
        try {
            noticeService.deleteNotice(noticeId);
            return RequestUtils.buildResponse("公告删除成功", 200);
        } catch (RuntimeException e) {
            return RequestUtils.buildResponse(e.getMessage(), 404);
        } catch (Exception e) {
            return RequestUtils.buildResponse("删除公告时发生异常", 500);
        }
    }
}
